#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
系统信息窗口

显示系统硬件信息的现代化窗口
"""

import tkinter as tk
from tkinter import ttk
import platform
import psutil
import datetime

# 导入ttkbootstrap美化
try:
    import ttkbootstrap as ttk
    from ttkbootstrap.constants import *
    from ttkbootstrap.style import Style
    from ttkbootstrap.icons import Icon
    import base64
    from io import BytesIO
    from PIL import Image, ImageTk
    BOOTSTRAP_AVAILABLE = True
except ImportError:
    BOOTSTRAP_AVAILABLE = False

# 导入配置
from settings import BASE_DIR, FONT_FAMILY, FONT_SIZE_NORMAL, FONT_SIZE_BOLD, COLORS, WINDOW_BG_COLOR
from utils.window_utils import calculate_window_size, center_window
from utils.logger import logger
from utils.icon_utils import get_icon_error


class SystemInfoWindow:
    """系统信息窗口"""
    
    def __init__(self, parent=None):
        """
        初始化系统信息窗口
        
        Args:
            parent: 父窗口
        """
        self.parent = parent
        
        # 创建窗口
        if BOOTSTRAP_AVAILABLE:
            if parent:
                self.window = ttk.Toplevel(parent)
            else:
                # 如果没有父窗口，创建一个独立的窗口
                self.window = tk.Toplevel()
                # 应用ttkbootstrap样式
                self.style = Style(theme='cosmo')
                # 将样式应用到窗口
                self.window.configure(bg=self.style.colors.bg)
        else:
            self.window = tk.Toplevel(parent) if parent else tk.Tk()
        
        self.window.title("系统信息")
        
        # 设置窗口大小和位置
        width, height = calculate_window_size(
            width_percent=0.6,
            height_percent=0.7
        )
        self.window.geometry(f"{width}x{height}")
        center_window(self.window)
        
        # 使窗口居中（只有在有父窗口时才设置transient）
        if parent:
            self.window.transient(parent)
        
        # 创建界面
        self.create_widgets()
        
        # 加载系统信息
        self.load_system_info()
    
    def create_widgets(self):
        """创建界面组件"""
        # 创建主框架
        if BOOTSTRAP_AVAILABLE:
            main_frame = ttk.Frame(self.window, padding="0")
        else:
            main_frame = tk.Frame(self.window, bg=WINDOW_BG_COLOR)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建TabBar
        self.create_tabbar(main_frame)
        
        # 创建内容区域
        self.create_content_area(main_frame)
        
        # 添加窗口关闭事件处理
        self.window.protocol("WM_DELETE_WINDOW", self.window.destroy)
        
        # 初始化动态图标数据
        self.dynamic_icons = {}
        self.update_interval = 1000  # 1秒更新一次
        self.current_selected = "CPU"  # 默认选中CPU
        
        # 创建性能页面
        self.create_performance_tab()
    
    def create_tabbar(self, parent):
        """创建TabBar"""
        if BOOTSTRAP_AVAILABLE:
            tab_frame = ttk.Frame(parent)
        else:
            tab_frame = tk.Frame(parent, bg=WINDOW_BG_COLOR)
        tab_frame.pack(fill=tk.X, padx=10, pady=(10, 0))
        
        # 创建标签页按钮
        tabs = ["性能", "进程", "启动", "用户", "详细信息", "服务"]
        self.tab_buttons = {}
        
        for i, tab_name in enumerate(tabs):
            if BOOTSTRAP_AVAILABLE:
                btn = ttk.Button(
                    tab_frame,
                    text=tab_name,
                    command=lambda t=tab_name: self.switch_tab(t),
                    bootstyle=PRIMARY if i == 0 else OUTLINE,
                    width=12
                )
            else:
                btn = tk.Button(
                    tab_frame,
                    text=tab_name,
                    command=lambda t=tab_name: self.switch_tab(t),
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                    bg=COLORS['primary'] if i == 0 else 'white',
                    fg='white' if i == 0 else COLORS['text'],
                    relief=tk.RAISED if i == 0 else tk.FLAT,
                    padx=15,
                    pady=5
                )
            
            btn.pack(side=tk.LEFT, padx=(0, 5))
            self.tab_buttons[tab_name] = btn
        
        self.current_tab = "性能"
    
    def create_content_area(self, parent):
        """创建内容区域"""
        if BOOTSTRAP_AVAILABLE:
            self.content_frame = ttk.Frame(parent, padding="10")
        else:
            self.content_frame = tk.Frame(parent, bg=WINDOW_BG_COLOR, padx=10, pady=10)
        self.content_frame.pack(fill=tk.BOTH, expand=True)
    
    def switch_tab(self, tab_name):
        """切换标签页"""
        # 更新按钮样式
        for name, btn in self.tab_buttons.items():
            if BOOTSTRAP_AVAILABLE:
                if name == tab_name:
                    btn.configure(bootstyle=PRIMARY)
                else:
                    btn.configure(bootstyle=OUTLINE)
            else:
                if name == tab_name:
                    btn.configure(bg=COLORS['primary'], fg='white', relief=tk.RAISED)
                else:
                    btn.configure(bg='white', fg=COLORS['text'], relief=tk.FLAT)
        
        # 清空内容区域
        for widget in self.content_frame.winfo_children():
            widget.destroy()
        
        # 根据标签页创建内容
        if tab_name == "性能":
            self.create_performance_tab()
        else:
            # 其他标签页暂时显示占位内容
            if BOOTSTRAP_AVAILABLE:
                placeholder = ttk.Label(
                    self.content_frame,
                    text=f"{tab_name} 页面开发中...",
                    font=(FONT_FAMILY, FONT_SIZE_BOLD),
                    bootstyle=SECONDARY
                )
            else:
                placeholder = tk.Label(
                    self.content_frame,
                    text=f"{tab_name} 页面开发中...",
                    font=(FONT_FAMILY, FONT_SIZE_BOLD),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['text']
                )
            placeholder.pack(expand=True)
        
        self.current_tab = tab_name
    
    def create_performance_tab(self):
        """创建性能标签页"""
        # 创建左右分栏
        if BOOTSTRAP_AVAILABLE:
            left_frame = ttk.Frame(self.content_frame, width=200)
            right_frame = ttk.Frame(self.content_frame)
        else:
            left_frame = tk.Frame(self.content_frame, width=200, bg=WINDOW_BG_COLOR)
            right_frame = tk.Frame(self.content_frame, bg=WINDOW_BG_COLOR)
        
        left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 创建左侧资源列表
        self.create_resource_list(left_frame)
        
        # 创建右侧详细信息
        self.create_detail_view(right_frame)
    
    def create_resource_list(self, parent):
        """创建左侧资源列表"""
        if BOOTSTRAP_AVAILABLE:
            list_frame = ttk.LabelFrame(parent, text="资源", padding="10")
        else:
            list_frame = tk.LabelFrame(
                parent,
                text="资源",
                font=(FONT_FAMILY, FONT_SIZE_BOLD),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['primary'],
                padx=10,
                pady=10
            )
        list_frame.pack(fill=tk.BOTH, expand=True)
        
        # 资源项目
        resources = [
            ("CPU", "cpu_percent", "blue"),
            ("内存", "memory_percent", "green"),
            ("磁盘", "disk_percent", "orange"),
            ("网络", "network_active", "purple"),
            ("GPU", "gpu_percent", "red")
        ]
        
        self.resource_items = {}
        
        for i, (name, key, color) in enumerate(resources):
            # 创建资源项目框架
            item_frame = tk.Frame(list_frame, bg='white' if BOOTSTRAP_AVAILABLE else WINDOW_BG_COLOR)
            item_frame.pack(fill=tk.X, pady=2)
            
            # 创建动态图标
            icon_canvas = self.create_dynamic_icon(item_frame, width=50, height=25, color=color)
            icon_canvas.resource_type = name.lower()  # 设置资源类型
            icon_canvas.pack(side=tk.LEFT, padx=(0, 10))
            
            # 创建标签
            if BOOTSTRAP_AVAILABLE:
                label = ttk.Label(
                    item_frame,
                    text=name,
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bootstyle=PRIMARY if name == "CPU" else SECONDARY
                )
                value_label = ttk.Label(
                    item_frame,
                    text="获取中...",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL - 2)
                )
            else:
                label = tk.Label(
                    item_frame,
                    text=name,
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['primary'] if name == "CPU" else COLORS['text']
                )
                value_label = tk.Label(
                    item_frame,
                    text="获取中...",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL - 2),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['text']
                )
            
            label.pack(side=tk.LEFT, padx=(0, 10))
            value_label.pack(side=tk.LEFT)
            
            # 绑定点击事件
            def make_click_handler(resource_name):
                def handler(event):
                    self.select_resource(resource_name)
                return handler
            
            item_frame.bind("<Button-1>", make_click_handler(name))
            label.bind("<Button-1>", make_click_handler(name))
            value_label.bind("<Button-1>", make_click_handler(name))
            
            # 保存引用
            self.resource_items[key] = {
                'frame': item_frame,
                'canvas': icon_canvas,
                'label': label,
                'value_label': value_label,
                'color': color,
                'name': name
            }
        
        # 开始更新动态图标
        self.update_dynamic_icons()
    
    def create_detail_view(self, parent):
        """创建右侧详细信息视图"""
        if BOOTSTRAP_AVAILABLE:
            detail_frame = ttk.LabelFrame(parent, text="详细信息", padding="15")
        else:
            detail_frame = tk.LabelFrame(
                parent,
                text="详细信息",
                font=(FONT_FAMILY, FONT_SIZE_BOLD),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['primary'],
                padx=15,
                pady=15
            )
        detail_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建标题区域
        self.create_detail_header(detail_frame)
        
        # 创建大图表区域
        self.create_large_chart(detail_frame)
        
        # 创建详细信息区域
        self.create_detail_info(detail_frame)
    
    def create_detail_header(self, parent):
        """创建详细信息标题"""
        header_frame = tk.Frame(parent, bg='white' if BOOTSTRAP_AVAILABLE else WINDOW_BG_COLOR)
        header_frame.pack(fill=tk.X, pady=(0, 15))
        
        if BOOTSTRAP_AVAILABLE:
            title_label = ttk.Label(
                header_frame,
                text="CPU",
                font=(FONT_FAMILY, FONT_SIZE_BOLD + 2, "bold"),
                bootstyle=PRIMARY
            )
            subtitle_label = ttk.Label(
                header_frame,
                text="12th Gen Intel(R) Core(TM) i5-12490F",
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                bootstyle=SECONDARY
            )
        else:
            title_label = tk.Label(
                header_frame,
                text="CPU",
                font=(FONT_FAMILY, FONT_SIZE_BOLD + 2, "bold"),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['primary']
            )
            subtitle_label = tk.Label(
                header_frame,
                text="12th Gen Intel(R) Core(TM) i5-12490F",
                font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['text']
            )
        
        title_label.pack(anchor=tk.W)
        subtitle_label.pack(anchor=tk.W)
        
        self.detail_title = title_label
        self.detail_subtitle = subtitle_label
    
    def create_large_chart(self, parent):
        """创建大图表"""
        chart_frame = tk.Frame(parent, bg='white' if BOOTSTRAP_AVAILABLE else WINDOW_BG_COLOR)
        chart_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 15))
        
        # 创建图表容器
        self.chart_container = chart_frame
        
        # 初始化图表数据
        self.chart_data = []
        self.disk_activity_data = []
        self.disk_transfer_data = []
        self.max_data_points = 60  # 60秒的数据
        
        # 创建默认的CPU图表
        self.create_cpu_chart()
    
    def create_cpu_chart(self):
        """创建CPU图表"""
        # 清空容器
        for widget in self.chart_container.winfo_children():
            widget.destroy()
        
        # 创建CPU图表画布
        self.large_chart = tk.Canvas(
            self.chart_container,
            height=200,
            bg='white',
            highlightthickness=1,
            highlightbackground='lightgray'
        )
        self.large_chart.pack(fill=tk.BOTH, expand=True)
    
    def create_disk_charts(self):
        """创建磁盘双图表"""
        # 清空容器
        for widget in self.chart_container.winfo_children():
            widget.destroy()
        
        # 创建两个图表框架
        top_chart_frame = tk.Frame(self.chart_container, bg='white')
        bottom_chart_frame = tk.Frame(self.chart_container, bg='white')
        
        top_chart_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 5))
        bottom_chart_frame.pack(fill=tk.BOTH, expand=True, pady=(5, 0))
        
        # 活动时间图表
        self.activity_chart = tk.Canvas(
            top_chart_frame,
            height=100,
            bg='white',
            highlightthickness=1,
            highlightbackground='lightgray'
        )
        self.activity_chart.pack(fill=tk.BOTH, expand=True)
        
        # 传输速率图表
        self.transfer_chart = tk.Canvas(
            bottom_chart_frame,
            height=100,
            bg='white',
            highlightthickness=1,
            highlightbackground='lightgray'
        )
        self.transfer_chart.pack(fill=tk.BOTH, expand=True)
        
        # 绑定悬停事件
        self.bind_chart_hover_events()
        
        # 初始化图表数据
        self.disk_activity_data = []
        self.disk_transfer_data = []
        
        # 延迟添加标签，确保图表尺寸已确定
        self.window.after(100, self.add_chart_labels)
    
    def add_chart_labels(self):
        """添加图表标签"""
        # 活动时间图表标签
        self.activity_chart.create_text(10, 15, text="活动时间", anchor=tk.W, font=('Arial', 10, 'bold'))
        self.activity_chart.create_text(self.activity_chart.winfo_width()-10, 15, text="100%", anchor=tk.E, font=('Arial', 10))
        self.activity_chart.create_text(10, self.activity_chart.winfo_height()-10, text="60秒", anchor=tk.W, font=('Arial', 10))
        self.activity_chart.create_text(self.activity_chart.winfo_width()-10, self.activity_chart.winfo_height()-10, text="0", anchor=tk.E, font=('Arial', 10))
        
        # 传输速率图表标签
        self.transfer_chart.create_text(10, 15, text="磁盘传输速率", anchor=tk.W, font=('Arial', 10, 'bold'))
        self.transfer_chart.create_text(self.transfer_chart.winfo_width()-10, 15, text="10 MB/秒", anchor=tk.E, font=('Arial', 10))
        self.transfer_chart.create_text(10, self.transfer_chart.winfo_height()-10, text="60秒", anchor=tk.W, font=('Arial', 10))
        self.transfer_chart.create_text(self.transfer_chart.winfo_width()-10, self.transfer_chart.winfo_height()-10, text="0", anchor=tk.E, font=('Arial', 10))
    
    def bind_chart_hover_events(self):
        """绑定图表悬停事件"""
        # 活动时间图表悬停提示
        self.activity_chart.bind("<Enter>", lambda e: self.show_tooltip(e, "磁盘处理读取或写入请求的时间百分比"))
        self.activity_chart.bind("<Leave>", lambda e: self.hide_tooltip())
        
        # 传输速率图表悬停提示
        self.transfer_chart.bind("<Enter>", lambda e: self.show_tooltip(e, "此磁盘的读取和写入活动"))
        self.transfer_chart.bind("<Leave>", lambda e: self.hide_tooltip())
    
    def show_tooltip(self, event, text):
        """显示悬停提示"""
        self.tooltip = tk.Toplevel()
        self.tooltip.wm_overrideredirect(True)
        self.tooltip.wm_geometry(f"+{event.x_root+10}+{event.y_root+10}")
        
        label = tk.Label(
            self.tooltip,
            text=text,
            bg='lightyellow',
            fg='black',
            font=('Arial', 9),
            padx=5,
            pady=3,
            relief=tk.SOLID,
            borderwidth=1
        )
        label.pack()
    
    def hide_tooltip(self):
        """隐藏悬停提示"""
        if hasattr(self, 'tooltip'):
            self.tooltip.destroy()
            delattr(self, 'tooltip')
    
    def create_detail_info(self, parent):
        """创建详细信息"""
        info_frame = tk.Frame(parent, bg='white' if BOOTSTRAP_AVAILABLE else WINDOW_BG_COLOR)
        info_frame.pack(fill=tk.X)
        
        # 创建两列信息
        left_info = tk.Frame(info_frame, bg='white' if BOOTSTRAP_AVAILABLE else WINDOW_BG_COLOR)
        right_info = tk.Frame(info_frame, bg='white' if BOOTSTRAP_AVAILABLE else WINDOW_BG_COLOR)
        
        left_info.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        right_info.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 详细信息标签（根据选中的资源动态显示）
        self.detail_info_labels = {
            "CPU": [
                ("利用率", "cpu_percent"),
                ("速度", "cpu_speed"),
                ("进程", "process_count"),
                ("线程", "thread_count"),
                ("句柄", "handles"),
                ("正常运行时间", "uptime"),
                ("基准速度", "base_speed"),
                ("插槽", "sockets"),
                ("内核", "cores"),
                ("逻辑处理器", "logical_processors"),
                ("虚拟化", "virtualization"),
                ("L1 缓存", "l1_cache"),
                ("L2 缓存", "l2_cache"),
                ("L3 缓存", "l3_cache")
            ],
            "内存": [
                ("使用中", "cpu_percent"),
                ("已压缩", "cpu_speed"),
                ("可用", "process_count"),
                ("速度", "thread_count"),
                ("已提交", "uptime"),
                ("已缓存", "base_speed")
            ],
            "磁盘": [
                ("活动时间", "activity_time"),
                ("平均响应时间", "response_time"),
                ("读取速度", "read_speed"),
                ("写入速度", "write_speed"),
                ("容量", "capacity"),
                ("已格式化", "formatted"),
                ("系统磁盘", "system_disk"),
                ("页面文件", "page_file"),
                ("类型", "disk_type")
            ]
        }
        
        # 默认显示CPU信息
        info_items = self.detail_info_labels.get("CPU", [])
        
        self.detail_labels = {}
        
        for i, (label_text, key) in enumerate(info_items):
            frame = left_info if i < 3 else right_info
            
            if BOOTSTRAP_AVAILABLE:
                label = ttk.Label(
                    frame,
                    text=f"{label_text}:",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bootstyle=SECONDARY
                )
                value_label = ttk.Label(
                    frame,
                    text="获取中...",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL)
                )
            else:
                label = tk.Label(
                    frame,
                    text=f"{label_text}:",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['text']
                )
                value_label = tk.Label(
                    frame,
                    text="获取中...",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['text']
                )
            
            label.pack(anchor=tk.W, pady=2)
            value_label.pack(anchor=tk.W, pady=2)
            
            self.detail_labels[key] = value_label
        
        # 开始更新详细信息
        self.update_detail_info()
    
    def select_resource(self, resource_name):
        """选择资源"""
        self.current_selected = resource_name
        
        # 更新左侧资源列表的选中状态
        for key, item in self.resource_items.items():
            if item['name'] == resource_name:
                if BOOTSTRAP_AVAILABLE:
                    item['label'].configure(bootstyle=PRIMARY)
                else:
                    item['label'].configure(fg=COLORS['primary'])
            else:
                if BOOTSTRAP_AVAILABLE:
                    item['label'].configure(bootstyle=SECONDARY)
                else:
                    item['label'].configure(fg=COLORS['text'])
        
        # 更新右侧详细信息
        self.update_detail_view(resource_name)
        
        # 更新详细信息标签
        self.update_detail_labels(resource_name)
    
    def update_detail_labels(self, resource_name):
        """更新详细信息标签"""
        try:
            # 获取新的标签信息
            info_items = self.detail_info_labels.get(resource_name, self.detail_info_labels["CPU"])
            
            # 更新标签文本
            for i, (label_text, key) in enumerate(info_items):
                if key in self.detail_labels:
                    # 找到对应的标签并更新文本
                    for widget in self.detail_labels[key].master.winfo_children():
                        if isinstance(widget, (tk.Label, ttk.Label)):
                            if widget != self.detail_labels[key]:
                                widget.configure(text=f"{label_text}:")
                                break
        except Exception as e:
            logger.error(f"更新详细信息标签失败: {e}")
    
    def update_detail_view(self, resource_name):
        """更新详细信息视图"""
        if resource_name == "CPU":
            self.detail_title.configure(text="CPU")
            self.detail_subtitle.configure(text="12th Gen Intel(R) Core(TM) i5-12490F")
            # 切换到CPU图表
            self.create_cpu_chart()
        elif resource_name == "内存":
            self.detail_title.configure(text="内存")
            self.detail_subtitle.configure(text="16 GB DDR4")
            # 切换到CPU图表（内存使用相同的图表样式）
            self.create_cpu_chart()
        elif resource_name == "磁盘":
            self.detail_title.configure(text="磁盘 0 (C: D:)")
            self.detail_subtitle.configure(text="ZHITAI Ti600 1TB")
            # 切换到磁盘双图表
            self.create_disk_charts()
        elif resource_name == "网络":
            self.detail_title.configure(text="网络")
            self.detail_subtitle.configure(text="Wi-Fi 6")
            # 切换到CPU图表（网络使用相同的图表样式）
            self.create_cpu_chart()
        elif resource_name == "GPU":
            self.detail_title.configure(text="GPU")
            self.detail_subtitle.configure(text="NVIDIA GeForce RTX 4060")
            # 切换到CPU图表（GPU使用相同的图表样式）
            self.create_cpu_chart()
    
    def update_detail_info(self):
        """更新详细信息"""
        try:
            # 检查窗口是否还存在
            if not hasattr(self, 'window') or not self.window.winfo_exists():
                return
            
            if self.current_selected == "CPU":
                # 更新CPU信息
                if 'cpu_percent' in self.detail_labels:
                    cpu_percent = psutil.cpu_percent(interval=0.1)
                    self.detail_labels['cpu_percent'].configure(text=f"{cpu_percent:.1f}%")
                
                if 'cpu_speed' in self.detail_labels:
                    cpu_freq = psutil.cpu_freq()
                    if cpu_freq:
                        self.detail_labels['cpu_speed'].configure(text=f"{cpu_freq.current:.2f} GHz")
                
                if 'process_count' in self.detail_labels:
                    process_count = len(psutil.pids())
                    self.detail_labels['process_count'].configure(text=str(process_count))
                
                if 'thread_count' in self.detail_labels:
                    # 获取真实线程数
                    thread_count = 0
                    for proc in psutil.process_iter(['pid', 'num_threads']):
                        try:
                            thread_count += proc.info['num_threads']
                        except (psutil.NoSuchProcess, psutil.AccessDenied):
                            pass
                    self.detail_labels['thread_count'].configure(text=str(thread_count))
                
                if 'handles' in self.detail_labels:
                    # 获取句柄数（Windows特定）
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            handles = 0
                            for proc in psutil.process_iter(['pid', 'num_handles']):
                                try:
                                    handles += proc.info['num_handles']
                                except (psutil.NoSuchProcess, psutil.AccessDenied):
                                    pass
                            self.detail_labels['handles'].configure(text=f"{handles:,}")
                        else:
                            self.detail_labels['handles'].configure(text="N/A")
                    except:
                        self.detail_labels['handles'].configure(text="N/A")
                
                if 'uptime' in self.detail_labels:
                    uptime = psutil.boot_time()
                    import datetime
                    boot_time = datetime.datetime.fromtimestamp(uptime)
                    now = datetime.datetime.now()
                    uptime_delta = now - boot_time
                    days = uptime_delta.days
                    hours, remainder = divmod(uptime_delta.seconds, 3600)
                    minutes, seconds = divmod(remainder, 60)
                    self.detail_labels['uptime'].configure(text=f"{days}:{hours:02d}:{minutes:02d}:{seconds:02d}")
                
                if 'base_speed' in self.detail_labels:
                    cpu_freq = psutil.cpu_freq()
                    if cpu_freq:
                        self.detail_labels['base_speed'].configure(text=f"{cpu_freq.max:.2f} GHz")
                
                if 'sockets' in self.detail_labels:
                    # 获取CPU插槽数
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'cpu', 'get', 'SocketDesignation', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            sockets = len([line for line in result.stdout.split('\n') if 'SocketDesignation=' in line and line.strip()])
                            self.detail_labels['sockets'].configure(text=str(sockets))
                        else:
                            self.detail_labels['sockets'].configure(text="1")
                    except:
                        self.detail_labels['sockets'].configure(text="1")
                
                if 'cores' in self.detail_labels:
                    cores = psutil.cpu_count(logical=False)
                    self.detail_labels['cores'].configure(text=str(cores))
                
                if 'logical_processors' in self.detail_labels:
                    logical_processors = psutil.cpu_count(logical=True)
                    self.detail_labels['logical_processors'].configure(text=str(logical_processors))
                
                if 'virtualization' in self.detail_labels:
                    # 检查虚拟化支持
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'cpu', 'get', 'VirtualizationFirmwareEnabled', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            if 'TRUE' in result.stdout.upper():
                                self.detail_labels['virtualization'].configure(text="已启用")
                            else:
                                self.detail_labels['virtualization'].configure(text="已禁用")
                        else:
                            self.detail_labels['virtualization'].configure(text="已启用")
                    except:
                        self.detail_labels['virtualization'].configure(text="已启用")
                
                if 'l1_cache' in self.detail_labels:
                    # 获取L1缓存信息
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'cpu', 'get', 'L1CacheSize', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            for line in result.stdout.split('\n'):
                                if 'L1CacheSize=' in line:
                                    cache_size = line.split('=')[1].strip()
                                    if cache_size and cache_size != '':
                                        self.detail_labels['l1_cache'].configure(text=f"{cache_size} KB")
                                        break
                            else:
                                self.detail_labels['l1_cache'].configure(text="480 KB")
                        else:
                            self.detail_labels['l1_cache'].configure(text="480 KB")
                    except:
                        self.detail_labels['l1_cache'].configure(text="480 KB")
                
                if 'l2_cache' in self.detail_labels:
                    # 获取L2缓存信息
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'cpu', 'get', 'L2CacheSize', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            for line in result.stdout.split('\n'):
                                if 'L2CacheSize=' in line:
                                    cache_size = line.split('=')[1].strip()
                                    if cache_size and cache_size != '':
                                        self.detail_labels['l2_cache'].configure(text=f"{cache_size} KB")
                                        break
                            else:
                                self.detail_labels['l2_cache'].configure(text="7.5 MB")
                        else:
                            self.detail_labels['l2_cache'].configure(text="7.5 MB")
                    except:
                        self.detail_labels['l2_cache'].configure(text="7.5 MB")
                
                if 'l3_cache' in self.detail_labels:
                    # 获取L3缓存信息
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'cpu', 'get', 'L3CacheSize', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            for line in result.stdout.split('\n'):
                                if 'L3CacheSize=' in line:
                                    cache_size = line.split('=')[1].strip()
                                    if cache_size and cache_size != '':
                                        self.detail_labels['l3_cache'].configure(text=f"{cache_size} KB")
                                        break
                            else:
                                self.detail_labels['l3_cache'].configure(text="20.0 MB")
                        else:
                            self.detail_labels['l3_cache'].configure(text="20.0 MB")
                    except:
                        self.detail_labels['l3_cache'].configure(text="20.0 MB")
            
            elif self.current_selected == "内存":
                # 更新内存信息
                memory = psutil.virtual_memory()
                if 'cpu_percent' in self.detail_labels:
                    self.detail_labels['cpu_percent'].configure(text=f"{memory.percent:.1f}%")
                
                if 'cpu_speed' in self.detail_labels:
                    # 显示已压缩内存（Windows特定）
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'OS', 'get', 'TotalVisibleMemorySize,FreePhysicalMemory', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            compressed = 0
                            for line in result.stdout.split('\n'):
                                if 'FreePhysicalMemory=' in line:
                                    free_kb = int(line.split('=')[1].strip())
                                    compressed = (memory.total - memory.available) - (free_kb * 1024)
                                    break
                            self.detail_labels['cpu_speed'].configure(text=f"{compressed / (1024**3):.1f} GB")
                        else:
                            self.detail_labels['cpu_speed'].configure(text="0.0 GB")
                    except:
                        self.detail_labels['cpu_speed'].configure(text="0.0 GB")
                
                if 'process_count' in self.detail_labels:
                    self.detail_labels['process_count'].configure(text=f"{memory.available / (1024**3):.1f} GB")
                
                if 'thread_count' in self.detail_labels:
                    # 显示内存速度（DDR类型）
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'memorychip', 'get', 'Speed', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            for line in result.stdout.split('\n'):
                                if 'Speed=' in line and line.strip():
                                    speed = line.split('=')[1].strip()
                                    if speed and speed != '':
                                        self.detail_labels['thread_count'].configure(text=f"{speed} MHz")
                                        break
                            else:
                                self.detail_labels['thread_count'].configure(text="DDR4")
                        else:
                            self.detail_labels['thread_count'].configure(text="DDR4")
                    except:
                        self.detail_labels['thread_count'].configure(text="DDR4")
                
                if 'uptime' in self.detail_labels:
                    # 显示已提交内存
                    committed = memory.used + memory.available
                    self.detail_labels['uptime'].configure(text=f"{committed / (1024**3):.1f} GB")
                
                if 'base_speed' in self.detail_labels:
                    # 显示已缓存内存
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            result = subprocess.run(['wmic', 'OS', 'get', 'FreePhysicalMemory', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            cached = 0
                            for line in result.stdout.split('\n'):
                                if 'FreePhysicalMemory=' in line:
                                    free_kb = int(line.split('=')[1].strip())
                                    cached = memory.available - (free_kb * 1024)
                                    break
                            self.detail_labels['base_speed'].configure(text=f"{cached / (1024**3):.1f} GB")
                        else:
                            self.detail_labels['base_speed'].configure(text="0.0 GB")
                    except:
                        self.detail_labels['base_speed'].configure(text="0.0 GB")
            
            elif self.current_selected == "磁盘":
                # 更新磁盘信息
                try:
                    import platform
                    if platform.system() == 'Windows':
                        disk_usage = psutil.disk_usage('C:\\')
                    else:
                        disk_usage = psutil.disk_usage('/')
                    
                    # 获取真实的磁盘IO数据
                    disk_io = psutil.disk_io_counters()
                    if disk_io:
                        # 计算磁盘活动百分比（基于IO时间）
                        activity_percent = min(100, (disk_io.read_time + disk_io.write_time) / 1000.0)
                        
                        # 计算平均响应时间
                        total_ops = disk_io.read_count + disk_io.write_count
                        if total_ops > 0:
                            response_time = (disk_io.read_time + disk_io.write_time) / total_ops
                        else:
                            response_time = 0
                        
                        # 计算读取和写入速度（基于字节数）
                        read_speed = disk_io.read_bytes / 1024  # KB
                        write_speed = disk_io.write_bytes / 1024  # KB
                    else:
                        activity_percent = 0
                        response_time = 0
                        read_speed = 0
                        write_speed = 0
                    
                    # 获取磁盘详细信息
                    disk_type = "SSD (NVMe)"  # 默认值
                    try:
                        import platform
                        if platform.system() == 'Windows':
                            import subprocess
                            # 获取磁盘类型
                            result = subprocess.run(['wmic', 'diskdrive', 'get', 'MediaType,Size', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            for line in result.stdout.split('\n'):
                                if 'MediaType=' in line:
                                    media_type = line.split('=')[1].strip()
                                    if 'SSD' in media_type.upper():
                                        disk_type = "SSD (NVMe)"
                                    elif 'HDD' in media_type.upper():
                                        disk_type = "HDD"
                                    break
                            
                            # 更新磁盘标题
                            if hasattr(self, 'detail_subtitle'):
                                self.detail_subtitle.configure(text=disk_type)
                    except:
                        pass
                    
                    if 'activity_time' in self.detail_labels:
                        self.detail_labels['activity_time'].configure(text=f"{activity_percent:.1f}%", font=('Segoe UI', 10, 'bold'))
                    
                    if 'response_time' in self.detail_labels:
                        self.detail_labels['response_time'].configure(text=f"{response_time:.1f} 毫秒", font=('Segoe UI', 10, 'bold'))
                    
                    if 'read_speed' in self.detail_labels:
                        self.detail_labels['read_speed'].configure(text=f"{read_speed:.0f} KB/秒", font=('Segoe UI', 10, 'bold'))
                    
                    if 'write_speed' in self.detail_labels:
                        self.detail_labels['write_speed'].configure(text=f"{write_speed:.0f} KB/秒", font=('Segoe UI', 10, 'bold'))
                    
                    if 'capacity' in self.detail_labels:
                        self.detail_labels['capacity'].configure(text=f"{disk_usage.total / (1024**3):.0f} GB", font=('Segoe UI', 10, 'normal'))
                    
                    if 'formatted' in self.detail_labels:
                        self.detail_labels['formatted'].configure(text=f"{disk_usage.total / (1024**3):.0f} GB", font=('Segoe UI', 10, 'normal'))
                    
                    if 'system_disk' in self.detail_labels:
                        self.detail_labels['system_disk'].configure(text="是", font=('Segoe UI', 10, 'normal'))
                    
                    if 'page_file' in self.detail_labels:
                        self.detail_labels['page_file'].configure(text="是", font=('Segoe UI', 10, 'normal'))
                    
                    if 'disk_type' in self.detail_labels:
                        self.detail_labels['disk_type'].configure(text=disk_type, font=('Segoe UI', 10, 'normal'))
                    
                    # 更新磁盘图表数据
                    self.update_disk_charts(activity_percent, read_speed, write_speed)
                    
                except Exception as e:
                    logger.error(f"更新磁盘信息失败: {e}")
            
        except Exception as e:
            logger.error(f"更新详细信息失败: {e}")
        
        # 安排下次更新
        self.window.after(self.update_interval, self.update_detail_info)
    
    def update_disk_charts(self, activity_percent, read_speed, write_speed):
        """更新磁盘图表"""
        try:
            if not hasattr(self, 'activity_chart') or not self.activity_chart:
                return
            
            # 添加新数据点
            self.disk_activity_data.append(activity_percent)
            self.disk_transfer_data.append((read_speed, write_speed))
            
            # 保持最大数据点数
            if len(self.disk_activity_data) > self.max_data_points:
                self.disk_activity_data.pop(0)
                self.disk_transfer_data.pop(0)
            
            # 更新活动时间图表
            self.update_activity_chart()
            
            # 更新传输速率图表
            self.update_transfer_chart()
            
        except Exception as e:
            logger.error(f"更新磁盘图表失败: {e}")
    
    def update_activity_chart(self):
        """更新活动时间图表"""
        try:
            if not hasattr(self, 'activity_chart') or not self.activity_chart:
                return
            
            # 清空画布
            self.activity_chart.delete("all")
            
            # 获取画布尺寸
            width = self.activity_chart.winfo_width()
            height = self.activity_chart.winfo_height()
            
            if width <= 1 or height <= 1:
                return
            
            # 绘制白色背景
            self.activity_chart.create_rectangle(0, 0, width, height, fill='white', outline='')
            
            # 绘制网格线
            for i in range(0, height, 20):
                self.activity_chart.create_line(0, i, width, i, fill='lightgray', width=1)
            
            for i in range(0, width, 20):
                self.activity_chart.create_line(i, 0, i, height, fill='lightgray', width=1)
            
            # 绘制数据线
            if len(self.disk_activity_data) > 1:
                points = []
                for i, val in enumerate(self.disk_activity_data):
                    x = (i / (len(self.disk_activity_data) - 1)) * (width - 20) + 10
                    y = height - 10 - (val / 100.0) * (height - 20)
                    points.extend([x, y])
                
                if points:
                    # 绘制数据线（绿色细线，不填充）
                    self.activity_chart.create_line(points, fill='green', width=1, smooth=True)
            
            # 添加四角标签（任务管理器样式）
            self.activity_chart.create_text(10, 15, text="活动时间", anchor=tk.W, font=('Segoe UI', 10, 'normal'), fill='black')
            self.activity_chart.create_text(width - 10, 15, text="100%", anchor=tk.E, font=('Segoe UI', 10, 'normal'), fill='black')
            self.activity_chart.create_text(10, height - 10, text="60秒", anchor=tk.W, font=('Segoe UI', 10, 'normal'), fill='black')
            self.activity_chart.create_text(width - 10, height - 10, text="0", anchor=tk.E, font=('Segoe UI', 10, 'normal'), fill='black')
                
        except Exception as e:
            logger.error(f"更新活动时间图表失败: {e}")
    
    def update_transfer_chart(self):
        """更新传输速率图表"""
        try:
            if not hasattr(self, 'transfer_chart') or not self.transfer_chart:
                return
            
            # 清空画布
            self.transfer_chart.delete("all")
            
            
            # 获取画布尺寸
            width = self.transfer_chart.winfo_width()
            height = self.transfer_chart.winfo_height()
            
            if width <= 1 or height <= 1:
                return
            
            # 绘制白色背景
            self.transfer_chart.create_rectangle(0, 0, width, height, fill='white', outline='')
            
            # 绘制网格线
            for i in range(0, height, 20):
                self.transfer_chart.create_line(0, i, width, i, fill='lightgray', width=1)
            
            for i in range(0, width, 20):
                self.transfer_chart.create_line(i, 0, i, height, fill='lightgray', width=1)
            
            # 绘制读取和写入数据线
            if len(self.disk_transfer_data) > 1:
                # 读取数据线
                read_points = []
                write_points = []
                
                for i, (read_speed, write_speed) in enumerate(self.disk_transfer_data):
                    x = (i / (len(self.disk_transfer_data) - 1)) * (width - 20) + 10
                    
                    # 转换为MB/s并限制在10MB/s以内
                    read_mb = min(read_speed / 1024, 10)
                    write_mb = min(write_speed / 1024, 10)
                    
                    read_y = height - 10 - (read_mb / 10.0) * (height - 20)
                    write_y = height - 10 - (write_mb / 10.0) * (height - 20)
                    
                    read_points.extend([x, read_y])
                    write_points.extend([x, write_y])
                
                if read_points:
                    # 绘制读取数据线（绿色实线）
                    self.transfer_chart.create_line(read_points, fill='green', width=1, smooth=True)
                
                if write_points:
                    # 绘制写入数据线（绿色虚线）
                    self.transfer_chart.create_line(write_points, fill='green', width=1, smooth=True, dash=(5, 5))
            
            # 添加四角标签（任务管理器样式）
            self.transfer_chart.create_text(10, 15, text="磁盘传输速率", anchor=tk.W, font=('Segoe UI', 10, 'normal'), fill='black')
            self.transfer_chart.create_text(width - 10, 15, text="10 MB/秒", anchor=tk.E, font=('Segoe UI', 10, 'normal'), fill='black')
            self.transfer_chart.create_text(10, height - 10, text="60秒", anchor=tk.W, font=('Segoe UI', 10, 'normal'), fill='black')
            self.transfer_chart.create_text(width - 10, height - 10, text="0", anchor=tk.E, font=('Segoe UI', 10, 'normal'), fill='black')
                
        except Exception as e:
            logger.error(f"更新传输速率图表失败: {e}")
    
    def add_activity_chart_labels(self):
        """添加活动时间图表标签"""
        width = self.activity_chart.winfo_width()
        height = self.activity_chart.winfo_height()
        
        if width > 1 and height > 1:
            self.activity_chart.create_text(10, 15, text="活动时间", anchor=tk.W, font=('Arial', 10, 'bold'))
            self.activity_chart.create_text(width-10, 15, text="100%", anchor=tk.E, font=('Arial', 10))
            self.activity_chart.create_text(10, height-10, text="60秒", anchor=tk.W, font=('Arial', 10))
            self.activity_chart.create_text(width-10, height-10, text="0", anchor=tk.E, font=('Arial', 10))
    
    def add_transfer_chart_labels(self):
        """添加传输速率图表标签"""
        width = self.transfer_chart.winfo_width()
        height = self.transfer_chart.winfo_height()
        
        if width > 1 and height > 1:
            self.transfer_chart.create_text(10, 15, text="磁盘传输速率", anchor=tk.W, font=('Arial', 10, 'bold'))
            self.transfer_chart.create_text(width-10, 15, text="10 MB/秒", anchor=tk.E, font=('Arial', 10))
            self.transfer_chart.create_text(10, height-10, text="60秒", anchor=tk.W, font=('Arial', 10))
            self.transfer_chart.create_text(width-10, height-10, text="0", anchor=tk.E, font=('Arial', 10))
    
    def create_dynamic_icon(self, parent, width=60, height=40, color='blue'):
        """创建动态图标（类似任务管理器的波形图）"""
        canvas = tk.Canvas(
            parent,
            width=width,
            height=height,
            bg='white',
            highlightthickness=0,
            relief=tk.FLAT
        )
        
        # 绘制波形图
        points = []
        for i in range(0, width, 4):
            import random
            y = height // 2 + random.randint(-height//4, height//4)
            points.extend([i, y])
        
        if points:
            canvas.create_line(points, fill=color, width=2, smooth=True)
        
        return canvas
    
    
    def update_dynamic_icons(self):
        """更新动态图标"""
        try:
            # 检查窗口是否还存在
            if not hasattr(self, 'window') or not self.window.winfo_exists():
                return
            
            # 更新CPU使用率
            if 'cpu_percent' in self.resource_items:
                cpu_percent = psutil.cpu_percent(interval=0.1)
                self.resource_items['cpu_percent']['value_label'].config(
                    text=f"{cpu_percent:.1f}%"
                )
                self.update_waveform(self.resource_items['cpu_percent']['canvas'], cpu_percent)
                
                # 更新大图表（只有选中CPU时才更新）
                if self.current_selected == "CPU":
                    self.update_large_chart(cpu_percent)
            
            # 更新内存使用率
            if 'memory_percent' in self.resource_items:
                memory = psutil.virtual_memory()
                self.resource_items['memory_percent']['value_label'].config(
                    text=f"{memory.percent:.1f}%"
                )
                self.update_waveform(self.resource_items['memory_percent']['canvas'], memory.percent)
                
                # 更新大图表（只有选中内存时才更新）
                if self.current_selected == "内存":
                    self.update_large_chart(memory.percent)
            
            # 更新磁盘使用率
            if 'disk_percent' in self.resource_items:
                try:
                    # 在Windows上使用C盘，在Linux上使用根目录
                    import platform
                    if platform.system() == 'Windows':
                        disk_usage = psutil.disk_usage('C:\\')
                    else:
                        disk_usage = psutil.disk_usage('/')
                    disk_percent = (disk_usage.used / disk_usage.total * 100)
                    self.resource_items['disk_percent']['value_label'].config(
                        text=f"{disk_percent:.1f}%"
                    )
                    self.update_waveform(self.resource_items['disk_percent']['canvas'], disk_percent)
                except Exception as e:
                    self.resource_items['disk_percent']['value_label'].config(text="未知")
            
            # 更新网络状态
            if 'network_active' in self.resource_items:
                try:
                    net_io = psutil.net_io_counters()
                    # 简单的网络活动指示
                    network_activity = (net_io.bytes_sent + net_io.bytes_recv) % 100
                    self.resource_items['network_active']['value_label'].config(
                        text="活跃" if network_activity > 50 else "空闲"
                    )
                    self.update_waveform(self.resource_items['network_active']['canvas'], network_activity)
                except:
                    self.resource_items['network_active']['value_label'].config(text="未知")
            
            # 更新GPU使用率
            if 'gpu_percent' in self.resource_items:
                # 尝试获取GPU信息
                try:
                    import platform
                    if platform.system() == 'Windows':
                        import subprocess
                        # 使用nvidia-smi获取GPU使用率
                        result = subprocess.run(['nvidia-smi', '--query-gpu=utilization.gpu', '--format=csv,noheader,nounits'], 
                                              capture_output=True, text=True, timeout=5)
                        if result.returncode == 0:
                            gpu_percent = float(result.stdout.strip())
                        else:
                            # 如果nvidia-smi不可用，使用WMI
                            result = subprocess.run(['wmic', 'path', 'win32_VideoController', 'get', 'Name', '/value'], 
                                                  capture_output=True, text=True, timeout=5)
                            gpu_percent = 0  # 默认值
                    else:
                        gpu_percent = 0
                except:
                    gpu_percent = 0
                
                self.resource_items['gpu_percent']['value_label'].config(
                    text=f"{gpu_percent}%"
                )
                self.update_waveform(self.resource_items['gpu_percent']['canvas'], gpu_percent)
            
        except Exception as e:
            logger.error(f"更新动态图标失败: {e}")
        
        # 安排下次更新
        self.window.after(self.update_interval, self.update_dynamic_icons)
    
    def update_large_chart(self, value):
        """更新大图表"""
        try:
            if not hasattr(self, 'large_chart') or not self.large_chart:
                return
            
            # 添加新数据点
            self.chart_data.append(value)
            
            # 保持最大数据点数
            if len(self.chart_data) > self.max_data_points:
                self.chart_data.pop(0)
            
            # 清空画布
            self.large_chart.delete("all")
            
            # 获取画布尺寸
            width = self.large_chart.winfo_width()
            height = self.large_chart.winfo_height()
            
            if width <= 1 or height <= 1:
                return
            
            # 绘制网格线
            for i in range(0, height, 20):
                self.large_chart.create_line(0, i, width, i, fill='lightgray', width=1)
            
            for i in range(0, width, 20):
                self.large_chart.create_line(i, 0, i, height, fill='lightgray', width=1)
            
            # 绘制数据线
            if len(self.chart_data) > 1:
                points = []
                for i, val in enumerate(self.chart_data):
                    x = (i / (len(self.chart_data) - 1)) * (width - 20) + 10
                    y = height - 10 - (val / 100.0) * (height - 20)
                    points.extend([x, y])
                
                if points:
                    # 绘制填充区域
                    fill_points = points[:]
                    fill_points.extend([width - 10, height - 10, 10, height - 10])
                    self.large_chart.create_polygon(fill_points, fill='lightblue', outline='')
                    
                    # 绘制数据线
                    self.large_chart.create_line(points, fill='blue', width=2, smooth=True)
            
            # 添加四角标签（任务管理器样式）
            self.large_chart.create_text(10, 15, text="% 利用率", anchor=tk.W, font=('Segoe UI', 10, 'normal'), fill='black')
            self.large_chart.create_text(width - 10, 15, text="100%", anchor=tk.E, font=('Segoe UI', 10, 'normal'), fill='black')
            self.large_chart.create_text(10, height - 10, text="60秒", anchor=tk.W, font=('Segoe UI', 10, 'normal'), fill='black')
            self.large_chart.create_text(width - 10, height - 10, text="0", anchor=tk.E, font=('Segoe UI', 10, 'normal'), fill='black')
            
        except Exception as e:
            logger.error(f"更新大图表失败: {e}")
    
    def update_waveform(self, canvas, value):
        """更新波形图"""
        try:
            canvas.delete("all")
            
            width = canvas.winfo_width()
            height = canvas.winfo_height()
            
            if width <= 1 or height <= 1:
                return
            
            # 根据值调整波形幅度
            amplitude = (value / 100.0) * (height // 2)
            
            # 生成波形点
            points = []
            for i in range(0, width, 2):
                import math
                import random
                # 使用正弦波 + 随机噪声
                base_y = height // 2
                wave_y = base_y + math.sin(i * 0.1) * amplitude * 0.5
                noise_y = random.randint(-int(amplitude * 0.3), int(amplitude * 0.3))
                y = wave_y + noise_y
                y = max(2, min(height - 2, y))  # 限制在画布范围内
                points.extend([i, y])
            
            if points:
                # 根据资源类型选择颜色
                if hasattr(canvas, 'resource_type'):
                    if canvas.resource_type == 'cpu':
                        color = 'blue'
                    elif canvas.resource_type == '内存':
                        color = 'green'
                    elif canvas.resource_type == '磁盘':
                        color = 'orange'
                    elif canvas.resource_type == '网络':
                        color = 'purple'
                    elif canvas.resource_type == 'gpu':
                        color = 'red'
                    else:
                        color = 'blue'
                else:
                    color = 'blue'
                
                canvas.create_line(points, fill=color, width=2, smooth=True)
                
        except Exception as e:
            logger.error(f"更新波形图失败: {e}")
    
    def create_info_section(self, title, info_dict, icon=None):
        """创建信息区块"""
        # 创建区块框架
        if BOOTSTRAP_AVAILABLE:
            section_frame = ttk.LabelFrame(
                self.scrollable_frame,
                text=title,
                padding="15",
                bootstyle=INFO
            )
        else:
            section_frame = tk.LabelFrame(
                self.scrollable_frame,
                text=title,
                font=(FONT_FAMILY, FONT_SIZE_BOLD, "bold"),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['primary'],
                padx=15,
                pady=15
            )
        section_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 创建信息网格
        row = 0
        for key, value in info_dict.items():
            # 标签
            if BOOTSTRAP_AVAILABLE:
                label = ttk.Label(
                    section_frame,
                    text=f"{key}:",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bootstyle=SECONDARY
                )
                value_label = ttk.Label(
                    section_frame,
                    text=str(value),
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL)
                )
            else:
                label = tk.Label(
                    section_frame,
                    text=f"{key}:",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['text']
                )
                value_label = tk.Label(
                    section_frame,
                    text=str(value),
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['text']
                )
            
            label.grid(row=row, column=0, sticky=tk.W, padx=(0, 10), pady=2)
            value_label.grid(row=row, column=1, sticky=tk.W, pady=2)
            row += 1
    
    def create_progress_section(self, title, progress_data):
        """创建进度条区块"""
        # 创建区块框架
        if BOOTSTRAP_AVAILABLE:
            section_frame = ttk.LabelFrame(
                self.scrollable_frame,
                text=title,
                padding="15",
                bootstyle=INFO
            )
        else:
            section_frame = tk.LabelFrame(
                self.scrollable_frame,
                text=title,
                font=(FONT_FAMILY, FONT_SIZE_BOLD, "bold"),
                bg=WINDOW_BG_COLOR,
                fg=COLORS['primary'],
                padx=15,
                pady=15
            )
        section_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 创建进度条
        for item_name, percentage in progress_data.items():
            # 标签
            if BOOTSTRAP_AVAILABLE:
                label = ttk.Label(
                    section_frame,
                    text=f"{item_name}:",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bootstyle=SECONDARY
                )
                progress = ttk.Progressbar(
                    section_frame,
                    length=200,
                    mode='determinate',
                    bootstyle=SUCCESS if percentage < 70 else WARNING if percentage < 90 else DANGER
                )
                percent_label = ttk.Label(
                    section_frame,
                    text=f"{percentage:.1f}%",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bootstyle=SUCCESS if percentage < 70 else WARNING if percentage < 90 else DANGER
                )
            else:
                label = tk.Label(
                    section_frame,
                    text=f"{item_name}:",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['text']
                )
                progress = tk.Canvas(
                    section_frame,
                    width=200,
                    height=20,
                    bg='lightgray',
                    highlightthickness=0
                )
                percent_label = tk.Label(
                    section_frame,
                    text=f"{percentage:.1f}%",
                    font=(FONT_FAMILY, FONT_SIZE_NORMAL, "bold"),
                    bg=WINDOW_BG_COLOR,
                    fg=COLORS['success'] if percentage < 70 else COLORS['warning'] if percentage < 90 else COLORS['error']
                )
            
            label.grid(row=len(section_frame.grid_slaves()), column=0, sticky=tk.W, padx=(0, 10), pady=5)
            progress.grid(row=len(section_frame.grid_slaves())-1, column=1, padx=(0, 10), pady=5)
            percent_label.grid(row=len(section_frame.grid_slaves())-2, column=2, sticky=tk.W, pady=5)
            
            # 设置进度条值
            if BOOTSTRAP_AVAILABLE:
                progress['value'] = percentage
            else:
                # 绘制进度条
                progress_width = int(200 * percentage / 100)
                color = COLORS['success'] if percentage < 70 else COLORS['warning'] if percentage < 90 else COLORS['error']
                progress.create_rectangle(0, 0, progress_width, 20, fill=color, outline='')
    
    def load_system_info(self):
        """加载系统信息"""
        try:
            # 新的系统信息窗口不需要加载静态信息
            # 所有信息都是动态更新的
            pass
        except Exception as e:
            logger.error(f"获取系统信息失败: {e}")


def open_system_info_window(parent=None):
    """打开系统信息窗口"""
    try:
        window = SystemInfoWindow(parent)
        return window
    except Exception as e:
        logger.error(f"打开系统信息窗口失败: {e}")
        return None


if __name__ == "__main__":
    # 测试窗口
    window = SystemInfoWindow()
    window.window.mainloop()
